package com.hzeport.bgs22emduty.util;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.dto.DutyScheduleExcelFailVO;
import com.hzeport.bgs22emduty.entity.*;
import com.hzeport.bgs22emduty.enums.DTypeEnum;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
import com.hzeport.bgs22emduty.enums.DutyTypeEnum;
import com.hzeport.bgs22emduty.outbound.*;

import com.hzeport.bgs22emduty.service.BaseDeptInfoService;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author ping
 */

@Slf4j
public class ExcelZGDataVerifyHandler extends AnalysisEventListener<DutyScheduleExcelFailVO> {

    private final List<DutyScheduleExcelFailVO> allList = new ArrayList<>();



    /**
     * 用于存储校验成功的数据，持久化到 Excel 文件中
     */
    private final List<DutyScheduleExcelFailVO> users = new ArrayList<>();

    private final DutyScheduleInfoRepository dutyScheduleInfoService;

    private final DutyScheduleInfo dutyScheduleInfo;

    private final BaseDeptInfoRepository baseDeptInfoRepository;
    private final BaseDeptInfoService baseDeptInfoService;

    private final BasePersonInfoRepository basePersonInfoRepository;

    private final String uploadDir;

    private final  UserInfoDetailVO userInfoDetail;

    private final ParamDutyRepository paramDutyRepository;
    private final DutyScheduleInfoRepository dutyScheduleInfoRepository;
    private final DutySignInfoRepository dutySignInfoRepository;
    private final GuavacacheUtils guavacacheUtils;

    private  final DutyScheduleSetCustomRepository dutyScheduleSetCustomRepository;
    private HttpServletResponse response;

    /**
     * 用于存储校验失败的数据，持久化到 Excel 文件中
     */
    private final List<DutyScheduleExcelFailVO> errorList = new ArrayList<>();

    public ExcelZGDataVerifyHandler(DutyScheduleInfo dutyScheduleInfo, DutyScheduleInfoRepository dutyScheduleInfoService, BaseDeptInfoRepository baseDeptInfoRepository, BasePersonInfoRepository basePersonInfoRepository, String uploadDir, UserInfoDetailVO userInfoDetail
            , BaseDeptInfoService baseDeptInfoService, ParamDutyRepository paramDutyRepository, DutyScheduleInfoRepository dutyScheduleInfoRepository, DutySignInfoRepository dutySignInfoRepository, DutyScheduleSetCustomRepository dutyScheduleSetCustomRepository, HttpServletResponse response, DutyScheduleSetCustomRepository scheduleSetCustomRepository, GuavacacheUtils guavacacheUtils) {
        this.dutyScheduleInfoService = dutyScheduleInfoService;
        this.dutyScheduleInfo = dutyScheduleInfo;
        this.uploadDir = uploadDir;
        this.baseDeptInfoRepository=baseDeptInfoRepository;
        this.basePersonInfoRepository=basePersonInfoRepository;
        this.userInfoDetail = userInfoDetail;
        this.baseDeptInfoService=baseDeptInfoService;
        this.paramDutyRepository = paramDutyRepository;
        this.dutyScheduleInfoRepository = dutyScheduleInfoRepository;
        this.dutySignInfoRepository=dutySignInfoRepository;
        this.dutyScheduleSetCustomRepository = dutyScheduleSetCustomRepository;
        this.response=response;

        this.guavacacheUtils = guavacacheUtils;
    }

    @Override
    public void invoke(DutyScheduleExcelFailVO user, AnalysisContext context) {
        if (user.getDutyTime()!=null){
            int index = user.getDutyTime().indexOf("(");
            if ( index !=-1){
                user.setDutyTime(user.getDutyTime().substring(0,index));
            }
        }

        if (user.getDDept()!=null){
            int indexDept = user.getDDept().indexOf("(");
            if ( indexDept !=-1){
                user.setDDept(user.getDDept().substring(0,indexDept));
            }
        }


        DutyScheduleExcelFailVO violations = violations(user);
        if (violations!=null){
            if (!StringUtils.isEmpty(violations.getE())) {
                // 处理校验失败数据的逻辑
                errorList.add(user);
            } else {
                // 处理正确数据的逻辑
                users.add(user);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doAfterAllAnalysed(AnalysisContext context) {
        String filePath = uploadDir;
        String filename = UUID.randomUUID() + ".xlsx";
        String name = filePath + File.separator + filename;
        try {
            //将校验失败的数据导出到Excel文件中，并在文件中标识出错误的原因

            //失败数据为空则导入TFGN
            List<DutyScheduleInfo> students = new ArrayList<>();
            List<DutyScheduleExcelFailVO> dutyScheduleExcelFailVOS=new ArrayList<>();
            Map<String,DutyScheduleExcelFailVO> dutyScheduleExcelFailVOMap=new HashMap<>();
            for (DutyScheduleExcelFailVO studentExcel : users) {
                DutyScheduleExcelFailVO dutyScheduleExcelFailVO=dutyScheduleExcelFailVOMap.get(studentExcel.getDDay()+"|"+studentExcel.getSType()+"|"+studentExcel.getDType()+"|"+studentExcel.getDUserjob()+"|"+studentExcel.getDutyTime());
                if (dutyScheduleExcelFailVO==null){
//                        dutyScheduleExcelFailVO
                    dutyScheduleExcelFailVOMap.put(studentExcel.getDDay()+"|"+studentExcel.getSType()+"|"+studentExcel.getDType()+"|"+studentExcel.getDUserjob()+"|"+studentExcel.getDutyTime(),studentExcel);
                }else {
                    DutyScheduleExcelFailVO temp=new DutyScheduleExcelFailVO();
                    temp.setDDay(studentExcel.getDDay());
                    temp.setSType(studentExcel.getSType());
                    temp.setDType(studentExcel.getDType());
                    temp.setDUserjob(studentExcel.getDUserjob());
                    temp.setDutyTime(studentExcel.getDutyTime());
                    temp.setNeedClear(1);
                    dutyScheduleExcelFailVOMap.put(studentExcel.getDDay()+"|"+studentExcel.getSType()+"|"+studentExcel.getDType()+"|"+studentExcel.getDUserjob()+"|"+studentExcel.getDutyTime(),temp);
                }
            }
            for (String key : dutyScheduleExcelFailVOMap.keySet()) {
                dutyScheduleExcelFailVOS.add(dutyScheduleExcelFailVOMap.get(key));
            }
            for (DutyScheduleExcelFailVO studentExcel : dutyScheduleExcelFailVOS) {


                studentExcel.setE( "成功" );
                allList.add( studentExcel );
                DutyScheduleInfo dutyScheduleInfo = new DutyScheduleInfo();
                BeanUtils.copyProperties(studentExcel,dutyScheduleInfo);
                String stype="";
                switch (studentExcel.getSType()){
                    case "工作日班":
                        stype="1";
                        break;
                    case  "节假日班":
                        stype="2";
                        break;
                    case  "重要时期班":
                        stype="3";
                        break;
                    case  "周末班":
                        stype="4";
                        break;
                }
                dutyScheduleInfo.setSType(stype);
                LocalDateTime localDateTime=LocalDateTime.ofInstant(studentExcel.getDDay().toInstant(), ZoneId.systemDefault());
                dutyScheduleInfo.setCustomId(userInfoDetail.getCustomscode());
                dutyScheduleInfo.setDDay(localDateTime.toLocalDate());
                dutyScheduleInfo.setCustomName(userInfoDetail.getCustomsName());
                ParamDuty paramDuty=paramDutyRepository.getOne(new LambdaQueryWrapper<ParamDuty>()
                        .eq(ParamDuty::getDDept,userInfoDetail.getCustomscode())
                        .eq(ParamDuty::getDType, DTypeEnum.TYPE_AFTERNOON.getCodeByValue(studentExcel.getDutyTime())));
                if (paramDuty!=null) {
                    dutyScheduleInfo.setDutyTimesId(paramDuty.getId());
                    String dayOfWeek = DateUtil.getDaysOfWeek((long) localDateTime.getYear(), (long) localDateTime.getMonth().getValue(), localDateTime.getDayOfMonth());
                    dutyScheduleInfo.setDDayString(localDateTime.getMonth().getValue() + "月" + localDateTime.getDayOfMonth() + "日" + dayOfWeek);
                        DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm:ss");
                    dutyScheduleInfo.setDutyTimesString(paramDuty.getDStartTime() .format(format)+ "-" + paramDuty.getDEndTime().format(format));
                    dutyScheduleInfo.setDutyTimesString(DTypeEnum.TYPE_DAY_TIME.getValueByCode(paramDuty.getDType()) + "(" + dutyScheduleInfo.getDutyTimesString() + ")");
                    dutyScheduleInfo.setDutyParamType(paramDuty.getDType());
                    if (paramDuty.getDStartTime().compareTo(paramDuty.getDEndTime())<0) {
                        dutyScheduleInfo.setDStartDateTime(dutyScheduleInfo.getDDay().atTime(paramDuty.getDStartTime()));
                        dutyScheduleInfo.setDEndDateTime(dutyScheduleInfo.getDDay().atTime(paramDuty.getDEndTime()));
                    }else {
                        dutyScheduleInfo.setDStartDateTime(dutyScheduleInfo.getDDay().atTime(paramDuty.getDStartTime()));
                        dutyScheduleInfo.setDEndDateTime(dutyScheduleInfo.getDDay().plusDays(1l).atTime(paramDuty.getDEndTime()));
                    }
                }

//                    dutyScheduleInfo.setDType("1");
                List<BasePersonInfo> basePersonInfos = guavacacheUtils.getPersons().stream().filter(i->i.getUserno().equals(studentExcel.getDUserno())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(basePersonInfos)) {
                    basePersonInfos = basePersonInfos.stream().filter(i -> i.getDeptId() != null && guavacacheUtils.getDepts().stream().filter(j->j.getId().equals(
                            i.getDeptId())).findAny().orElse(null) != null).collect(Collectors.toList());
                    BasePersonInfo tempBasePerson = basePersonInfos.stream().filter(i -> "0".equals(i.getSideLine()))
                            .findAny().orElse(null);
                    if (tempBasePerson == null) {
                        tempBasePerson = basePersonInfos.get(0);
                    }
                    BasePersonInfo basePersonInfo = tempBasePerson;
                    BaseDeptInfo baseDeptInfo = guavacacheUtils.getDepts().stream().filter(j->j.getId().equals(
                            basePersonInfo.getDeptId())).findAny().orElse(null);
                    if (StringUtils.isEmpty(dutyScheduleInfo.getDDept())) {
                        dutyScheduleInfo.setDDeptname(baseDeptInfo.getDeptName());
                        dutyScheduleInfo.setDDept(baseDeptInfo.getId());
                    } else {
                        String customCode = this.userInfoDetail.getCustomscode();
//                            String customCode = "94480300-fca2-4268-86c2-4c13963bf4cb";
                        List<BaseDeptInfo> baseDeptInfos = guavacacheUtils.getDepts().stream().filter(j->j.getCustomId().equals(customCode)).collect(Collectors.toList());
                        DutyScheduleInfo finalDutyScheduleInfo = dutyScheduleInfo;
                        baseDeptInfos = baseDeptInfos.stream().filter(i->i.getDeptName()!=null).filter(i -> i.getDeptName().equals(finalDutyScheduleInfo.getDDept()))
                                .collect(Collectors.toList());
                        dutyScheduleInfo.setDDeptname(baseDeptInfos.get(0).getDeptName());
                        dutyScheduleInfo.setDDept(baseDeptInfos.get(0).getId());
                    }

                    if (StringUtils.isEmpty(dutyScheduleInfo.getDPhone())) {
                        dutyScheduleInfo.setDPhone(basePersonInfo.getPhone());
                    }
                    if (StringUtils.isEmpty(dutyScheduleInfo.getDPhoneLand())) {
                        dutyScheduleInfo.setDPhoneLand(basePersonInfo.getPhoneLand());
                    }
                    if (StringUtils.isEmpty(dutyScheduleInfo.getDUsername())) {
                        dutyScheduleInfo.setDUsername(basePersonInfo.getUsername());
                    }
                    if (StringUtils.isEmpty(dutyScheduleInfo.getDUserno())) {
                        dutyScheduleInfo.setDUserno(basePersonInfo.getUserno());
                    }
                    if (StringUtils.isEmpty(dutyScheduleInfo.getRankCode())) {
                        dutyScheduleInfo.setRankCode(basePersonInfo.getRankCode());
                    }
                    if (StringUtils.isEmpty(dutyScheduleInfo.getRankCode())) {
                        dutyScheduleInfo.setRankCode(basePersonInfo.getRankCode());
                    }
                    if (StringUtils.isEmpty(dutyScheduleInfo.getDutypost())) {
                        dutyScheduleInfo.setDutypost(basePersonInfo.getRankCode() != null ? getDupostByH4a(basePersonInfo.getRealRackCode()) : "");
                    }
                    if (StringUtils.isEmpty(dutyScheduleInfo.getPhoneShort())) {
                        dutyScheduleInfo.setPhoneShort(basePersonInfo.getPhoneShort());
                    }
                }
                dutyScheduleInfo.setCreateBy(userInfoDetail.getUserId());
                dutyScheduleInfo.setCreateTime(LocalDateTime.now());
                dutyScheduleInfo.setUpdateBy(userInfoDetail.getUserId());
                dutyScheduleInfo.setDOperatorName(userInfoDetail.getUserName());
                dutyScheduleInfo.setUpdateTime(LocalDateTime.now());
                dutyScheduleInfo.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                if (dutyScheduleInfo.getDType()!=null) {
                    dutyScheduleInfo.setDutyType(getDutyType(dutyScheduleInfo.getDUserjob()));
                    dutyScheduleInfo.setDType(getDType(dutyScheduleInfo.getDUserjob()));
                }
                if (paramDuty!=null&&dutyScheduleInfo.getDutyType()!=null){
                    dutyScheduleInfoService.remove(new LambdaUpdateWrapper<DutyScheduleInfo>()
                            .eq(DutyScheduleInfo::getDelFlag, "0").eq(DutyScheduleInfo::getDDay, localDateTime.toLocalDate())
                            .eq(DutyScheduleInfo::getDutyTimesId, paramDuty.getId())
                            .eq(DutyScheduleInfo::getDutyType, dutyScheduleInfo.getDutyType())
                            .eq(DutyScheduleInfo::getSType, dutyScheduleInfo.getSType())
                            .eq(DutyScheduleInfo::getCustomId, userInfoDetail.getCustomscode()));
                }
                if (studentExcel.getNeedClear()!=null&&studentExcel.getNeedClear()==1){
                    DutyScheduleInfo temp=new DutyScheduleInfo();
                    temp.setDDay(dutyScheduleInfo.getDDay());
                    dutyScheduleInfo=temp;
                    dutyScheduleInfo.setCreateBy(userInfoDetail.getUserId());
                    dutyScheduleInfo.setCreateTime(LocalDateTime.now());
                    dutyScheduleInfo.setUpdateBy(userInfoDetail.getUserId());
                    dutyScheduleInfo.setDOperatorName(userInfoDetail.getUserName());
                    dutyScheduleInfo.setUpdateTime(LocalDateTime.now());
                    dutyScheduleInfo.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                    dutyScheduleInfo.setCustomId(userInfoDetail.getCustomscode());
                    dutyScheduleInfo.setCustomName(userInfoDetail.getCustomsName());
                    dutyScheduleInfo.setIsWhite("1");
                }
                //todo
                students.add(dutyScheduleInfo);
            }
            dutyScheduleInfoService.saveOrUpdateBatch(students);
            List<DutySignInfo> dutySignInfos=new ArrayList<>();
            for (DutyScheduleInfo scheduleInfo:students){
                DutySignInfo info = dutySignInfoRepository.getOne(new LambdaQueryWrapper<DutySignInfo>()
                        .eq(DutySignInfo::getDId,scheduleInfo.getId()),false);
                if (info==null) {
                    if (!org.apache.commons.lang.StringUtils.isEmpty(dutyScheduleInfo.getDUserno())) {
                        DutySignInfo dutySignInfo = new DutySignInfo();
                        dutySignInfo.setDId(scheduleInfo.getId());
                        dutySignInfo.setCreateBy("sys");
                        dutySignInfo.setCreateTime(LocalDateTime.now());
                        dutySignInfo.setUpdateBy("sys");
                        dutySignInfo.setUpdateTime(LocalDateTime.now());
                        dutySignInfo.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                        dutySignInfos.add(dutySignInfo);
                    }
                }
            }
            if (!CollectionUtils.isEmpty(dutySignInfos)){
                dutySignInfoRepository.saveBatch(dutySignInfos);
            }

            BaseResult<String>  resultVO ;
            if(errorList.isEmpty()){
                resultVO = BaseResult.ok(null, "导入成功");
            }else {
                resultVO = BaseResult.failed(filename, "导入失败,错误条数"+errorList.size()+";正确条数"+users.size());
                EasyExcel.write(name, DutyScheduleExcelFailVO.class).sheet().doWrite(errorList);
            }

            String jsonObject= JSONObject.toJSONString(resultVO);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            try ( PrintWriter out = response.getWriter()) {
                out.append(jsonObject);
            } catch ( IOException e) {
                log.error("导入错误",e);
            }

        } catch (Exception e) {
            log.error("导入错误",e);
            throw new RuntimeException(filename);
        }
    }

    private String getDutyType(String dUserjob) {
        String result = "";

        switch (dUserjob) {
            case "署领导":
                result = DutyTypeEnum.GENERAL_ADMINISTRATION_LEADER.getValue();
                break;
            case "司局领导":
                result = DutyTypeEnum.DEPARTMENT_EXCHANGE.getValue();
                break;
            case "处领导":
                result = DutyTypeEnum.DIVISION_LEADER.getValue();
                break;
            case "主值班员":
                result = DutyTypeEnum.MASTER_DUTY.getValue();
                break;
            case "副值班员":
                result = DutyTypeEnum.DEPUTY_DUTY.getValue();
                break;
        }
        return result;
    }


    private String getDType(String dUserjob) {
        String result = "";

        switch (dUserjob) {
            case "署领导":
                result = "2";
                break;
            case "司局领导":
                result = "2";
                break;
            case "处领导":
                result = "2";
                break;
            case "主值班员":
                result = "1";
                break;
            case "副值班员":
                result = "1";
                break;
        }
        return result;
    }
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        // 处理异常情况
        ;
        throw exception;
    }

    private String getDupostByH4a(String rankCode) {
        String result = "";
        if (rankCode==null){
            return result;
        }
        switch (rankCode) {
            case "05":
                result = "厅局级正职";
                break;
            case "06":
                result = "厅局级副职";
                break;
            case "07":
                result = "处级人员";
                break;
            case "08":
                result = "处级人员";
                break;
            case "09":
                result = "科长级人员";
                break;
            case "10":
                result = "科长级人员";
                break;
            case "11":
                result = "科员";
                break;
            case "99":
                result = "无行政级别";
                break;
            default:
                return "其他";
        }
        return result;
    }


    private DutyScheduleExcelFailVO violations(DutyScheduleExcelFailVO user) {
        try {

            StringBuffer msg = new StringBuffer();
            if (StringUtils.isBlank(user.getSType()) && user.getDDay() == null && StringUtils.isBlank(user.getDutyTime())
                    && StringUtils.isBlank(user.getDUserjob()) && StringUtils.isBlank(user.getDUserno()) && StringUtils.isBlank(user.getDDept())
                    && StringUtils.isBlank(user.getDType())){
//                msg.append("|该行内容为空格，已过滤");
//                user.setE(!StringUtils.isEmpty(msg) ? String.valueOf(msg) : null);
//                return user;
                return null;
            }
            if (StringUtils.isEmpty(user.getSType())) {
                msg.append("|排班类型不能为空");
            } else {
                if (!Arrays.asList("工作日班","周末班", "节假日班", "重要时期班").contains(user.getSType())) {
                    msg.append("|排班类型只能为:工作日班/周末班/节假日班/重要时期班");
                }
            }
            if (user.getDDay() == null) {
                msg.append("|值班日期不能为空");
            }
            if (StringUtils.isEmpty(user.getDutyTime())) {
                msg.append("|值班时段不能为空");

            } else {
                int index = user.getDutyTime().indexOf("(");
                if ( index !=-1){
                    user.setDutyTime(user.getDutyTime().substring(0,index));
                }
                if (!Arrays.asList("上午", "下午", "白天", "夜间", "全天","其他").contains(user.getDutyTime())) {
                    msg.append("|值班时段只能为:上午/下午/白天/夜间/全天/其他");
                } else {
                    ParamDuty paramDuty = paramDutyRepository.getOne(new LambdaQueryWrapper<ParamDuty>()
                            .eq(ParamDuty::getDDept, userInfoDetail.getCustomscode())
                            .eq(ParamDuty::getDType, DTypeEnum.TYPE_AFTERNOON.getCodeByValue(user.getDutyTime())));
                    if (paramDuty == null) {
                        msg.append("|本关区未配置:" + user.getDutyTime() + "时段");
                    }
                }
            }
            if (StringUtils.isEmpty(user.getDUserjob())) {
                msg.append("|人员排班职级不能为空");
            } else {
                if (!Arrays.asList("署领导", "司局领导", "处领导", "主值班员", "副值班员").contains(user.getDUserjob())) {
                    msg.append("|人员排班职级只能为:署领导/司局领导/处领导/主值班员/副值班员");
                }
            }
            if (StringUtils.isEmpty(user.getDUserno())) {
                msg.append("|工号不能为空");
            } else {
                Long basePersonInfos = guavacacheUtils.getPersons().stream().filter(i->i.getUserno().equals(user.getDUserno())).count();
                if (basePersonInfos == 0) {
                    msg.append("|无该工号人员");
                }
            }
            if (StringUtils.isEmpty(user.getDDept())) {
//                msg.append("|值班部门不能为空");
            } else {
                String customCode = this.userInfoDetail.getCustomscode();
//                String customCode = "94480300-fca2-4268-86c2-4c13963bf4cb";
                List<BaseDeptInfo> baseDeptInfos = guavacacheUtils.getDepts().stream().filter(j->j.getCustomId().equals(customCode)).collect(Collectors.toList());
                if (!baseDeptInfos.stream().map(i -> i.getDeptName()).collect(Collectors.toList()).contains(user.getDDept())) {
                    msg.append("|本关区下无此部门名");
                }
            }
            if (StringUtils.isEmpty(user.getDType())) {
                msg.append("|值班类型不能为空");
            } else {
                if (!Arrays.asList("值班", "带班").contains(user.getDType())) {
                    msg.append("|值班类型只能为:值班/带班");
                }
            }
            DutyScheduleSetCustom dutyScheduleSetCustom = dutyScheduleSetCustomRepository.getOne(new LambdaQueryWrapper<DutyScheduleSetCustom>()
                    .and(wrapper ->
                            wrapper.le(DutyScheduleSetCustom::getStartDate, LocalDate.of(user.getDDay().getYear()+1900, user.getDDay().getMonth()+1, 1))
                                    .ge(DutyScheduleSetCustom::getEndDate, LocalDate.of(user.getDDay().getYear()+1900, user.getDDay().getMonth()+1, 1).plusMonths(1).minusDays(1).minusMonths(1))
                    )
                    .eq(DutyScheduleSetCustom::getCustomId,userInfoDetail.getCustomscode()
                    ));
            if (dutyScheduleSetCustom == null) {
                msg.append("|该时段没有进行过总体排班");
            }
//        String stype="";
//        if (StringUtils.isEmpty(user.getSType())) {
//
//        }else {
//            switch (user.getSType()) {
//                case "工作日班":
//                    stype = "1";
//                    break;
//                case "节假日班":
//                    stype = "2";
//                    break;
//                case "重要时期班":
//                    stype = "3";
//                    break;
//            }
//        }
//        LocalDateTime localDateTime=LocalDateTime.ofInstant(user.getDDay().toInstant(), ZoneId.systemDefault());
//        LocalDateTime startTime = LocalDateTime.of(localDateTime.toLocalDate(),LocalTime.MIN);
//        LocalDateTime endTime = LocalDateTime.of(localDateTime.toLocalDate(),LocalTime.MAX);
//        List<DutyScheduleInfo> scheduleInfoTimesId = dutyScheduleInfoRepository.list(new LambdaQueryWrapper<DutyScheduleInfo>()
//                .between(DutyScheduleInfo::getDDay, startTime,endTime)
//                .eq(DutyScheduleInfo::getCustomId,userInfoDetail.getCustomscode()));
//        if (scheduleInfoTimesId.size()>0){
//            if (!scheduleInfoTimesId.get(0).getSType().equals(stype)){
//                msg.append("|同一天内只能有一种排班类型");
//            }
//        }

//        String dutyType=null;
//        switch (user.getDType()){
//            case "值班":
//                dutyType="7";
//                break;
//            case "带班":
//                dutyType="6";
//                break;
//        }
//        ParamDuty paramDuty=paramDutyRepository.getOne(new LambdaQueryWrapper<ParamDuty>()
//                .eq(ParamDuty::getDDept,userInfoDetail.getCustomscode())
//                .eq(ParamDuty::getDType, DTypeEnum.TYPE_AFTERNOON.getCodeByValue(user.getDutyTime())));
//        DutyScheduleInfo scheduleInfo = dutyScheduleInfoRepository.getOne(new LambdaQueryWrapper<DutyScheduleInfo>()
//                .eq(DutyScheduleInfo::getSType, stype)
//                .eq(DutyScheduleInfo::getDutyTimesId, paramDuty.getId())
//                .between(DutyScheduleInfo::getDDay, startTime,endTime)
//                .eq(DutyScheduleInfo::getDutyType, dutyType),false);
//        if (scheduleInfo!=null){
//            msg.append("|该班次已存在值班人员");
//        }
            user.setE(!StringUtils.isEmpty(msg) ? String.valueOf(msg) : null);
            return user;
        }catch (Exception e){
            log.error("异常",e);
            user.setE("异常"+e.getMessage());
            return user;
        }
    }
    static <T> Predicate<T> distinctByKey(Function<? super T,?> ketExtractor){
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(ketExtractor.apply(t) , Boolean.TRUE) == null;
    }
}
